import Vue from "vue";
import Router from "vue-router";
import util from "@/libs";

Vue.use(Router);

// 鉴权
function isLogin() {
  return util.cookies.get("token");
}

// 环境配置
const _import = (function() {
  if (process.env.NODE_ENV === "development")
    return function(file) {
      return require("@/pages/" + file).default;
    };
  else {
    return function(file) {
      return () => import("@/pages/" + file);
    };
  }
})();

var router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "home",
      meta: {
        auth: true,
        title: "首页"
      },
      component: _import("home"),
      redirect: { name: "dashboard" },
      children: [
        {
          path: "dashboard",
          name: "dashboard",
          component: _import("home/dashboard")
        },
        {
          path: "user",
          name: "user",
          component: _import("home/user")
        },
        {
          path: "role",
          name: "role",
          component: _import("home/role")
        },
        {
          path: "share",
          name: "share",
          component: _import("home/share")
        },
        {
          path: "post",
          name: "post",
          component: _import("home/post")
        }
      ]
    },
    {
      path: "/login",
      name: "login",
      component: _import("login")
    },
    {
      path: "/register",
      name: "register",
      component: _import("register")
    },
    {
      path: "/findPwd",
      name: "findPwd",
      component: _import("findPwd")
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.auth)) {
    if (isLogin()) {
      next();
    } else {
      next({
        name: "login",
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next();
  }
});
export default router;
